package xin.tianhui.cloud.weblog.service.impl;

import xin.tianhui.cloud.weblog.model.dto.ChannelResultDTO;
import xin.tianhui.cloud.weblog.model.dto.ModelItemQueryDTO;
import xin.tianhui.cloud.weblog.model.dto.ModelItemResultDTO;
import xin.tianhui.cloud.weblog.model.po.ModelItem;
import xin.tianhui.cloud.weblog.mapper.ModelItemMapper;
import xin.tianhui.cloud.weblog.service.IChannelService;
import xin.tianhui.cloud.weblog.service.IModelItemService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 模型细分类 服务实现类
 * </p>
 *
 * @author junchen
 * @since 2018-04-21
 */
@Service
@CacheConfig(cacheNames="model",keyGenerator="keyGenerator")
public class ModelItemServiceImpl extends ServiceImpl<ModelItemMapper, ModelItem> implements IModelItemService {
	
	@Autowired
	private IChannelService channelService;
	
	@Cacheable
	@Override
	public List<ModelItemResultDTO> getModelItemList(ModelItemQueryDTO query) {
		ModelItem item = new ModelItem();
		if(query.getModelBid()!=null) {
			item.setModelId(query.getModelBid());
			item.setIsChannel(query.getIsChannel());
		}else {
			if(query.getChannelBid()!=null) {
				ChannelResultDTO channel = channelService.getChannelById(query.getChannelBid());
				if(channel!=null) {
					item.setModelId(channel.getModel().getBid());
					item.setIsChannel(0);
				}else {
					return Collections.emptyList();
				}
			}else {
				return Collections.emptyList();
			}
		}
		QueryWrapper<ModelItem> wrapper = new QueryWrapper<ModelItem>(item);
		wrapper.orderByAsc("priority");
		List<ModelItem> items = baseMapper.selectList(wrapper);
		List<ModelItemResultDTO> results = Optional.ofNullable(items).map(result->{
			List<ModelItemResultDTO> resultDTOs = Lists.newArrayList();
			result.forEach(r->{
				ModelItemResultDTO dto = new ModelItemResultDTO();
				dto.setField(r.getField());
				dto.setItemLabel(r.getItemLabel());
				dto.setDataType(r.getDataType());
				dto.setDefValue(r.getDefValue());
				dto.setIsDisplay(r.getIsDisplay());
				dto.setIsRequired(r.getIsRequired());
				dto.setIsSingle(r.getIsSingle());
				dto.setTextSize(r.getTextSize());
				resultDTOs.add(dto);
			});
			return resultDTOs;
		}).orElse(Collections.emptyList());
		return results;
	}

}
